from fastapi import APIRouter
from app.api.deps import CurrentUser, SessionDep
from app.crud.uc.partner_token import get_partner_token
from app.core.constants import ThirdPartner
from fastapi import HTTPException
from app.services.wp_service import query_wp_wallet
from app.core.logger import logger
from app.services.nft_service import get_nft_detail
from app.schemas.waveup.wp_wallet import WPWalletOut, WPWalletListReq
from app.crud.waveup.wp_wallet import qry_wp_wallet_list
from typing import List

router = APIRouter(tags=["wp-wallet"], prefix="/wp-wallet")

@router.post("/list")
async def get_wp_wallet_list(
    session: SessionDep,
    current_user: CurrentUser,
    req: WPWalletListReq,
):
    """
    获取WP流动性资产
    """
    resp = await get_wallet_list_local(
        session=session,
        current_user=current_user,
        page_no=req.pageNo,
        page_size=req.pageSize,
        product_ids=req.productIds,
    )
    return resp
    partner_token = await get_partner_token(
        session=session,
        uid=current_user.uid,
        partner=ThirdPartner.WaveUp,
    )
    if not partner_token:
        raise HTTPException(status_code=400, detail="Partner token not found")
    wp_wallet = await query_wp_wallet(
        pageNo=pageNo,
        pageSize=pageSize,
        accessToken=partner_token.accessToken,
        productIds=req.productIds,
    )
    if wp_wallet["rc"] != 0:
        logger.error(f"WaveUp流动性资产查询失败: {wp_wallet}")
        raise HTTPException(status_code=400, detail="流动性资产查询失败")
    
    # 本地缓存查询资产信息
    records = []
    for item in wp_wallet["data"]["records"]:
        # 查询藏品详情
        nft_detail = await get_nft_detail(
            session=session,
            productId=item["productId"],
            uid=current_user.uid,
        )
        if nft_detail:
            item = WPWalletOut(
                productId=item["productId"],
                assetAmount=item["assetAmount"],
                productName=nft_detail["productName"],
                imageUrl=nft_detail["imageUrl"],
                archiveId=nft_detail["archiveId"],
                minPrice=nft_detail["minPrice"],
            )
        else:
            logger.error(f"WaveUp藏品详情查询失败: {nft_detail}")
            # 剔除掉这个流动资产，不返回，继续下一个
            # 后续添加一个任务，异步更新数据库藏品信息
            continue
        records.append(item)
    
    wp_wallet["data"]["records"] = records

    return wp_wallet["data"]

async def get_wallet_list_local(
    session: SessionDep,
    current_user: CurrentUser,
    page_no: int = 1,
    page_size: int = 10,
    product_ids: List[str] = [],
):
    """
    获取WP流动性资产(本地缓存)
    """
    resp = await qry_wp_wallet_list(
        session=session,
        uid=current_user.uid,
        page_no=page_no,
        page_size=page_size,
        product_ids=product_ids,
    )
    records = []
    for item in resp["records"]:
        # 查询藏品详情
        nft_detail = await get_nft_detail(
            session=session,
            productId=item.productId,
            uid=current_user.uid,
        )
        if nft_detail:
            item = WPWalletOut(
                productId=item.productId,
                assetAmount=item.assetAmount,
                # productName=item.productName,
                productName=nft_detail["productName"],
                imageUrl=item.imageUrl,
                archiveId=nft_detail["archiveId"],
                minPrice=nft_detail["minPrice"],
            )
        records.append(item)
    
    resp["records"] = records
    return resp
